# import requests
# from src.config import API_KEY, SECRET_KEY
# import logging
# from src.utils.save_mp3_file import save_mp3_file
# ACCESS_TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'
# TTS_URL = 'https://tsn.baidu.com/text2audio'

# def get_access_token():
#     url = 'https://aip.baidubce.com/oauth/2.0/token'
#     params = {
#         'grant_type': 'client_credentials',
#         'client_id': API_KEY,
#         'client_secret': SECRET_KEY
#     }
#     response = requests.post(url, params)
#     response.raise_for_status()  # 如果请求失败，抛出异常
#     return response.json().get('access_token')

# def text_to_speech(text):
#     logging.info("Converting text to speech...")
#     access_token = get_access_token()
#     if not access_token:
#         raise Exception("Failed to retrieve access token.")
    
#     # 定义请求参数
#     params = {
#         'tex': text,
#         'tok': access_token,
#         'cuid': 'your_unique_cuid',
#         'ctp': 1,
#         'lan': 'zh',
#         'per': 106
#     }
    
#     # 使用data参数发送表单数据
#     response = requests.post(TTS_URL, data=params, stream=True)
    
#     if response.headers.get('Content-Type') == 'audio/mp3':
#         save_mp3_file(response.content, "answer_audio_records")
#         return response.content
#     else:
#         # 如果响应不是MP3，处理错误
#         error_msg = response.json().get('error_msg', 'Unknown error')
#         # raise Exception(f"Failed to convert text to speech: {error_msg}")
#         logging.error(f"Failed to convert text to speech: {error_msg}")
    
# if __name__ == "__main__":
#     # 测试代码
#     response_audio = text_to_speech("测试文本,测试文本,测试文本,测试文本,测试文本")
#     with open('output.mp3', 'wb') as f:
#         f.write(response_audio)


import aiohttp
import logging
from src.utils.save_mp3_file import save_mp3_file
from src.config import API_KEY, SECRET_KEY

ACCESS_TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'
TTS_URL = 'https://tsn.baidu.com/text2audio'

async def get_access_token():
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    params = {
        'grant_type': 'client_credentials',
        'client_id': API_KEY,
        'client_secret': SECRET_KEY
    }
    async with aiohttp.ClientSession() as session:
        async with session.post(url, data=params) as response:
            response.raise_for_status()  # 如果请求失败，抛出异常
            data = await response.json()
            return data.get('access_token')

async def text_to_speech(text):
    logging.info("Converting text to speech...")
    access_token = await get_access_token()
    if not access_token:
        raise Exception("Failed to retrieve access token.")
    
    params = {
        'tex': text,
        'tok': access_token,
        'cuid': 'your_unique_cuid',
        'ctp': 1,
        'lan': 'zh',
        'per': 106
    }
    
    async with aiohttp.ClientSession() as session:
        async with session.post(TTS_URL, data=params) as response:
            if response.headers.get('Content-Type') == 'audio/mp3':
                audio_content = await response.read()
                await save_mp3_file(audio_content, "answer_audio_records")
                return audio_content
            else:
                error_msg = await response.json()
                logging.error(f"Failed to convert text to speech: {error_msg.get('error_msg', 'Unknown error')}")
    
if __name__ == "__main__":
    # 测试代码
    import asyncio
    async def main():
        response_audio = await text_to_speech("测试文本,测试文本,测试文本,测试文本,测试文本")
        with open('output.mp3', 'wb') as f:
            f.write(response_audio)

    asyncio.run(main())
